package com.qen.segments;

import com.qen.common.BeetlUtils;
import com.qen.common.ClassDescHelper;
import lombok.Getter;
import org.beetl.sql.clazz.ColDesc;
import org.beetl.sql.clazz.kit.JavaType;
import org.beetl.sql.core.mapping.type.JavaSqlTypeHandler;

import java.io.Serializable;
import java.sql.JDBCType;
import java.util.Objects;

/**
 * 缓存
 *
 * @author licz
 * @since 1.0.0
 */
@Getter
public class SelectCache implements Serializable {

    /**
     * 实体类
     */
    private final Class<?> clazz;

    /**
     * 是否是主键
     */
    private final boolean isPk;

    /**
     * 查询字段
     */
    private final String column;

    /**
     * 字段类型
     */
    private final Class<?> columnType;

    /**
     * 查询字段 去除特殊符号 比如反引号,单引号,双引号等
     *
     * @see ClassDescHelper#getTargetColumn(Class, String)
     */
    private final String tagColumn;

    /**
     * 字段属性名
     */
    private final String columProperty;

    /**
     * 使用使用 hasTypeHandle
     */
    private final boolean hasTypeHandle;

    /**
     * tableFieldInfo中信息
     */
    private final Class<?> propertyType;
    private final JDBCType jdbcType;
    private final Class<? extends JavaSqlTypeHandler> typeHandlerClass;

    /**
     * 是否查询
     */
    private final boolean isSelect;

    public SelectCache(Class<?> clazz, boolean isPk, String column, Class<?> columnType, String columProperty, boolean isSelect, ColDesc col) {
        this.clazz = clazz;
        this.isPk = isPk;
        this.column = column;
        this.columnType = columnType;
        this.columProperty = columProperty;

        this.tagColumn = ClassDescHelper.getTargetColumn(clazz, column);
        this.isSelect = isSelect;
        if (Objects.isNull(col)) {
            this.hasTypeHandle = false;
            this.propertyType = null;
            this.jdbcType = null;
            this.typeHandlerClass = null;
        } else {
            int sqlType = col.getSqlType();
            Class<?> javaType = JavaType.jdbcJavaTypes.get(sqlType);
            this.propertyType = javaType;
            this.jdbcType = JDBCType.valueOf(sqlType);
            JavaSqlTypeHandler typeHandler = BeetlUtils.getJavaSqlTypeHandler(javaType);
            this.typeHandlerClass = typeHandler.getClass();
            this.hasTypeHandle = typeHandler != null;
        }
    }

    public JavaSqlTypeHandler getTypeHandler() {
        if (this.hasTypeHandle) {
            return BeetlUtils.getJavaSqlTypeHandler(propertyType);
        }
        return null;
    }
}
